package com.lincoln.redis.server.config;

import com.lincoln.config.StartRun;
import com.lincoln.redis.server.entity.User;
import com.lincoln.redis.server.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.stereotype.Component;

/**
 * 启动服务时执行
 *
 * @author lincoln
 */
@Component
@Order(value = 1)
public class Run extends StartRun {
    Logger logger = LoggerFactory.getLogger(Run.class);
    @Autowired
    UserService userService;

    @Override
    public void run(String... args) throws Exception {
        if (userService.findByName("admin") == null) {
            logger.info("未找到admin!");
            User user = new User();
            user.setUsername("admin");
            user.setPassword(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123456"));
            user.setEnabled(true);
            user.setAccountNonLocked(true);
            user.setCredentialsNonExpired(true);
            user.setAccountNonExpired(true);
            userService.save(user);
            user.getPermissions().add("admin");
            userService.save(user);
        }
    }
}
